package com.none.web.service.book.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.none.core.common.utils.DateUtil;
import com.none.core.common.utils.StringUtil;
import com.none.core.common.utils.TransactSQLInjectionUtil;
import com.none.core.exception.ValidateException;
import com.none.core.model.Pager;
import com.none.core.service.BaseServiceSupport;
import com.none.web.model.TBookcategory;
import com.none.web.model.TBookinfo;
import com.none.web.model.TBookstat;
import com.none.web.service.book.IBookAppService;
import com.none.web.service.book.IBookService;
@Service("bookService")
public class BookServiceImpl extends BaseServiceSupport implements IBookService {
	@Autowired
    JdbcTemplate jdbcTemplate;
	@Autowired
	IBookAppService bookAppService;
	
	/**
	 * 查询书籍类型列表
	 */
	@Override
	public Object searchBookcategorys() {
		String sql="select id,category from rgt_bookcategory";
		return this.jdbcTemplate.queryForList(sql);
	}
	
	/**
	 * 新增书籍
	 */
	@Override
	public boolean saveOrUpdateBook(TBookinfo bookInfo,Long timestamp) throws Exception {
		if(StringUtils.isBlank(bookInfo.getBook_mgrNo())){
			throw new ValidateException("books.mgrNoNull");
		}
		//新增时校验mgrNo唯一性
		if(bookInfo.getBook_sn()==null){
			bookInfo.setAddtime(new Timestamp(new Date().getTime()));
			List<Map<String,Object>> list=jdbcTemplate.queryForList("select book_sn from rgt_bookinfo where book_mgrNo='"+bookInfo.getBook_mgrNo()+"'");
			if(list!=null&&list.size()>0){
				throw new ValidateException("books.mgrNoExisted");
			}
		}else{
			List<Map<String,Object>> list=jdbcTemplate.queryForList("select book_sn from rgt_bookinfo where book_mgrNo='"+bookInfo.getBook_mgrNo()+"' and book_sn !="+bookInfo.getBook_sn());
			if(list!=null&&list.size()>0){
				throw new ValidateException("books.mgrNoExisted");
			}
			Map map=jdbcTemplate.queryForMap("select addtime from rgt_bookinfo where book_sn="+bookInfo.getBook_sn());
			bookInfo.setAddtime((Timestamp) map.get("addtime"));
		}
		if(StringUtils.isBlank(bookInfo.getBook_Name())){
			throw new ValidateException("books.nameNull");
		}
		if(bookInfo.getCatalog_id()==null){
			throw new ValidateException("books.categoryNull");
		}
		if(findEntity(TBookcategory.class, bookInfo.getCatalog_id())== null){
			throw new ValidateException("books.categoryNotExists");
		}
		if(bookInfo.getBook_vol()==null){
			throw new ValidateException("books.volNull");
		}
		if (StringUtils.isBlank(bookInfo.getBook_open())) {
			throw new ValidateException("books.isOpenNull");
		}
		//设置缺省图片
		if (StringUtils.isBlank(bookInfo.getBook_cover())) {
			bookInfo.setBook_cover("http://120.24.55.7:9191/freemarker/upload/bookCover.png");
		}
		if (StringUtils.isBlank(bookInfo.getBook_open())) {
			throw new ValidateException("books.isOpenNull");
		}
		if(timestamp!=null){
			bookInfo.setBook_publisher_year(new Timestamp(timestamp));
		}
		try {
				saveOrUpdateEntity(bookInfo);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ValidateException("common.illegalRequest");
		}
		
		//添加一本书后，如果有人设置了提醒，需要推送  20151014 bing
		int avi_book = bookInfo.getBook_vol()-getAvaiBooksNums(bookInfo.getBook_mgrNo());
		if(avi_book>0){
			bookAppService.savePushReminder(bookInfo.getBook_sn());
		}
		
		return true;
	}
	
	/**
	 * 删除书籍
	 */
	@Override
	public boolean delBookinfo(Integer id) throws Exception {
		if(id==null){
			throw new ValidateException("books.idIsNull");
		}
		if(!deleteEntity(TBookinfo.class, id)){
			throw new ValidateException("common.illegalRequest");
		}
		return true;
	}
	
	/**
	 * 查看书籍列表
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Object searchBooks(Pager pager, String keyword, Integer cateId,
			String fromDate, String toDate) throws Exception{
		List<TBookinfo> books=new ArrayList<TBookinfo>();
		boolean bool = TransactSQLInjectionUtil.sql_inj(StringUtil.toString(keyword)); //防止SQL注入
		if(bool){
			return books;
		}else{
			StringBuffer sql=new StringBuffer("select * from rgt_bookinfo t where 1=1 ");
			if(StringUtils.isNotBlank(keyword)){
				sql.append(" and t.book_Name like '%"+keyword+"%' ");
			}
			if(cateId!=null){
				sql.append(" and t.catalog_id="+cateId);
			}
			
			if (StringUtils.isNotBlank(fromDate)) {
				
				sql.append("  and t.addtime>='"+DateUtil.timeStampToDate(fromDate)+"'");
			}
			if(StringUtils.isNotBlank(toDate)) {
				sql.append("  and t.addtime<='"+DateUtil.timeStampToDate(toDate)+"'");
			}
			sql.append(" order by t.addtime desc");
			books=(List<TBookinfo>) this.getListBySql(pager, sql.toString(), TBookinfo.class);
		}
		
		return books;
	}
	
	/**
	 * 根据书籍ID查找书籍
	 * @param id
	 * @return
	 */
	@Override
	public Object searchBookById(Integer id) {
		return findEntity(TBookinfo.class, id);
	}
	
	/**
	 * 查看预约记录
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Object searchBookstats(Pager pager,Integer code) {
		List<TBookstat> bookstats=new ArrayList<TBookstat>();
		StringBuffer sql=new StringBuffer("select * from rgt_bookstat t where 1=1 ");
		if(code!=null){
			if(code==1){
				sql.append(" and t.BDetail_status=1");
			}else{
				sql.append(" and t.BDetail_status in (2,3,4)");
			}
		}
		sql.append(" order by t.BDetail_RgtDate desc");
		bookstats=(List<TBookstat>) this.getListBySql(pager, sql.toString(), TBookstat.class);
		return bookstats;
	}
	
	/**
	 * 取消预约 
	 */
	@Override
	public boolean editReserveCancell(Integer id) throws Exception {
		
		if(id==null){
			throw new ValidateException("books.idIsNull");
		}
		TBookstat bookstauts =findEntity(TBookstat.class, id);
		if(bookstauts.getBDetail_status()==6){
			throw new ValidateException("book.hasBeenCanceled");
		}else if(bookstauts.getBDetail_status()==2 ||bookstauts.getBDetail_status()==3||bookstauts.getBDetail_status()==4){
			throw new ValidateException("book.hasBeenCheckOut");
		}else if(bookstauts.getBDetail_status()==5){
			throw new ValidateException("book.hasBeenCheckIn");
		}
		
		String sql="update rgt_bookstat set BDetail_status=6,BDetail_cancelDate=now(),BDetail_Return='Y' where BDetail_Sn=? and BDetail_status =1";
		try {
			jdbcTemplate.update(sql,id);
		} catch (Exception e) {
			throw new ValidateException("common.illegalRequest");
		}
		
		//取消预约后，如果有人设置了提醒，需要推送  20151014 bing
		TBookstat bookStat = this.findEntity(TBookstat.class, id);
		if(bookStat!=null){
			bookAppService.savePushReminder(bookStat.getBDetail_BookSN());
		}
		return true;
	}
	
	/**
	 * 还书
	 */
	@Override
	public boolean editReturnedBook(Integer id) throws Exception {
		if(id==null){
			throw new ValidateException("books.idIsNull");
		}
		TBookstat bookstauts =findEntity(TBookstat.class, id);
		if(bookstauts.getBDetail_status()==5){
			throw new ValidateException("book.hasBeenCheckIn");
		}else if(bookstauts.getBDetail_status()==6){
			throw new ValidateException("book.hasBeenCanceled");
		}else if(bookstauts.getBDetail_status()==1){
			throw new ValidateException("book.checkout");
		}
		String sql="update rgt_bookstat set BDetail_status=5,BDetail_RelDate=now(),BDetail_Return='Y' where BDetail_Sn=? and BDetail_status in(2,3,4)";
		try {
			jdbcTemplate.update(sql,id);
		} catch (Exception e) {
			throw new ValidateException("common.illegalRequest");
		}
		
		//还书后，如果有人设置了提醒，需要推送  20151014 bing
		TBookstat bookStat = this.findEntity(TBookstat.class, id);
		if(bookStat!=null){
			bookAppService.savePushReminder(bookStat.getBDetail_BookSN());
		}
		return true;
	}
	
	/**
	 * 取书
	 */
	@Override
	public boolean editTakeBook(Integer id) throws Exception {
		if(id==null){
			throw new ValidateException("books.idIsNull");
		}
		TBookstat bookstauts =findEntity(TBookstat.class, id);
		if(bookstauts.getBDetail_status()==2 || bookstauts.getBDetail_status()==3 || bookstauts.getBDetail_status()==4){
			throw new ValidateException("book.hasBeenCheckOut");
		}else if(bookstauts.getBDetail_status()==5){
			throw new ValidateException("book.hasBeenCheckIn");
		}else if(bookstauts.getBDetail_status()==6){
			throw new ValidateException("book.hasBeenCanceled");
		}
		String sql="update rgt_bookstat set BDetail_status=2,BDetail_checkoutDate=now(),BDetail_RtnDate=date_add(now(), interval 30 day) where BDetail_Sn=? and BDetail_status=1";
		try {
			jdbcTemplate.update(sql,id);
		} catch (Exception e) {
			throw new ValidateException("common.illegalRequest");
		}
		return true;
	}
	
	/**
	 * 查询借出去和预约的书的数量（取消预约的除外）  Add by Bing 2015-09-23
	 * @param book_mgrNo
	 * @return
	 */
	private Integer getAvaiBooksNums(String book_mgrNo){
		StringBuffer sql = new StringBuffer();
		sql.append("select count(t.BDetail_Sn) nums from rgt_bookstat t where  t.BDetail_BookmgtNo='"+book_mgrNo+"' and t.BDetail_Return='N' and t.BDetail_status<>'6'");
		List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(sql.toString());
		Integer amount=0;
		if(listMapIsLike!=null && listMapIsLike.size()>0){
			amount=StringUtil.toInteger(listMapIsLike.get(0).get("nums"));
		}else{
			amount=0;
		}
		return amount;
	}
}
